//  <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
//
//          EXIF ReName
//          Copyright (C) 2007 - 2021 Ingemar Ceicer
//          https://gitlab.com/posktomten/exifrename2
//          ic_0002 (at) ceicer (dot) com
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 3
//   as published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
// <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
#include "exif.h"
#include "info.h"
#include "exifw.h"
#include "mainwindow.h"
#include "tabwidget.h"
#include "ui_mainwindow.h"
#include "inputdialogoffset.h"

QStringList MainWindow::changeExifManyFiles(QString offset)
{
    qInfo() << "HIT";
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Extensions");
    QStringList selectedfilters = settings.value("selectedfilters").toStringList();
    selectedfilters.sort(Qt::CaseInsensitive);
    settings.endGroup();
    QDir dir(QDir::home());
    QString home = QDir::toNativeSeparators(dir.absolutePath());
    settings.beginGroup("Path");
    QString openpath = settings.value("openpath", home).toString();
    settings.endGroup();
    QFileDialog * dialog = new QFileDialog(this);
//    dialog->setModal(false);
    dialog->setWindowIconText(tr("Select files to adjust EXIF Date/Time according to offset"));
    dialog->resize(900, 600);
    dialog->setViewMode(QFileDialog::Detail);
    dialog->setFileMode(QFileDialog::ExistingFiles);
    dialog->setWindowTitle(tr("Select file or files to be modified by offset"));
    settings.beginGroup("Tools");
    dialog->setOption(QFileDialog::DontUseNativeDialog, !settings.value("usenativedialog").toBool());
    bool useopenpath = settings.value("useopenpath", false).toBool();
    bool checkredtext = settings.value("checkredtext", false).toBool();
    bool displayfailure = settings.value("displayfailure", true).toBool();
    bool displaysuccess = settings.value("displaysuccess", false).toBool();
    settings.endGroup();
    settings.beginGroup("Extensions");
    QString selectednamefilter = settings.value("selectednamefilter", "tomt").toString();
    settings.endGroup();

    if(useopenpath) {
        if(!TabWidget::pathExist(openpath)) {
            dialog->setDirectory(home);
        } else if(openpath.isEmpty()) {
            dialog->setDirectory(home);
        } else {
            dialog->setDirectory(openpath);
        }
    } else {
        dialog->setDirectory(home);
    }

    QStringList fileNames;

    if(selectednamefilter != "tomt") {
        dialog->setNameFilters(QStringList() << selectednamefilter << selectedfilters);
    } else {
        dialog->setNameFilters(selectedfilters);
    }

    if(dialog->exec()) {
        fileNames = dialog->selectedFiles();
        int antal = fileNames.count();

        if(antal != 1) {
            ui->textBrowserMain->append(tr("Attempting to modify EXIF Date/Time in") + " " + QString::number(antal) + " " + tr("files"));
        } else {
            ui->textBrowserMain->append(tr("Attempting to modify EXIF Date/Time in") + " " + QString::number(antal) + " " + tr("file"));
        }

        int lyckade = 0;

        foreach(QString qfilename2, fileNames) {
            char *hittat = new char[20];
            QString *info = new QString;
            Exif exif;
            bool b = exif.getExif(qfilename2, hittat, info);
            QString qhittat;

            if(b) {
                qhittat = QString::fromLatin1(hittat);
                QRegExp rx("[0-9]{4}x[0-9]{2}x[0-9]{2}x[0-9]{2}x[0-9]{2}x[0-9]{2}");

                if(!rx.exactMatch(qhittat)) {
                    if(checkredtext) {
                        ui->textBrowserMain->setTextColor(QColor("red"));
                        ui->textBrowserMain->append(tr("No EXIF data found in") + " " +  " \"" + QDir::toNativeSeparators(qfilename2) + "\"");
                        ui->textBrowserMain->setTextColor(QColor("black"));
                    } else {
                        ui->textBrowserMain->append(tr("No EXIF data found in") + " " +  " \"" + QDir::toNativeSeparators(qfilename2) + "\"");
                    }

//                    ui->textBrowserMain->append("");
                    qInfo() << "HÄR" << fileNames.last();
                    fileNames.last() = "novaliddata";
                    b = false;
                }
            } else {
                if(checkredtext) {
                    ui->textBrowserMain->setTextColor(QColor("red"));
                    ui->textBrowserMain->append(tr("No EXIF data found in") + " \"" +  QDir::toNativeSeparators(qfilename2) + "\"");
                    ui->textBrowserMain->setTextColor(QColor("black"));
                } else {
                    ui->textBrowserMain->append(tr("No EXIF data found in") + " \"" +  QDir::toNativeSeparators(qfilename2) + "\"");
                }

//                ui->textBrowserMain->append("");
                qInfo() << "HÄR" << fileNames.last();
                fileNames.last() = "novaliddata";
            }

            if(b) {
//                ui->textBrowserMain->append(*info);
                qhittat.replace(4, 1, '-');
                qhittat.replace(7, 1, '-');
                qhittat.replace(10, 1, ' ');
                qhittat.replace(13, 1, ':');
                qhittat.replace(16, 1, ':');
                qint64 sec = offset.toLongLong();
                QString format = "yyyy-MM-dd HH:mm:ss";
                QDateTime org_dt = QDateTime::fromString(qhittat, format);
                org_dt = org_dt.addSecs(sec);
                qhittat = org_dt.toString(format);
                qhittat.remove('-');
                qhittat.remove(':');
                qhittat.remove(' ');
                string str_filename = qfilename2.toStdString();
                char *cchar_filename = new char[str_filename.size()];
                strcpy(cchar_filename, str_filename.c_str());
                string str_newdatetime = qhittat.toStdString();
                char *cchar_newdatetime = new char[str_newdatetime.size()];
                strcpy(cchar_newdatetime, str_newdatetime.c_str());
                char *info = new char[50];
                Exifw exifw;
                bool lyckats = exifw.setExif(cchar_filename, cchar_newdatetime, info);
                std::string tmp = (char*)info;
                QString qinfo = QString::fromStdString(tmp);

                if(!lyckats) {
                    if(displayfailure) {
                        if(checkredtext) {
                            ui->textBrowserMain->setTextColor(QColor("red"));
                            ui->textBrowserMain->append(qinfo + " \"" + QDir::toNativeSeparators(qfilename2) + "\"");
                            ui->textBrowserMain->setTextColor(QColor("black"));
                        } else {
                            ui->textBrowserMain->append(qinfo + " \"" + QDir::toNativeSeparators(qfilename2) + "\"");
                        }
                    }
                }

                if(lyckats) {
                    if(displaysuccess) {
                        ui->textBrowserMain->append(qinfo + " \"" + QDir::toNativeSeparators(qfilename2) + "\"");
                    }

                    lyckade++;
                }

                QDir dir = dialog->directory();
                openpath = dir.path();
                settings.beginGroup("Path");
                settings.setValue("openpath", openpath);
                settings.endGroup();
                settings.beginGroup("Extensions");
                settings.setValue("selectednamefilter", dialog->selectedNameFilter());
                settings.endGroup();
            }
        }

        if(lyckade != 1) {
            ui->textBrowserMain->append(tr("Managed to change EXIF Date/Time in") + " " + QString::number(lyckade) + " " + tr("files"));
        } else {
            ui->textBrowserMain->append(tr("Managed to change EXIF Date/Time in") + " " + QString::number(lyckade) + " " + tr("file"));
        }

        ui->textBrowserMain->append("");
    }

    fileNames.removeAll("novaliddata");
    return fileNames;
}
